<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增客户信息')"/>
</head>
<body>
<form class="layui-form">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">客户名字：</label>
                <div class="layui-input-block">
                    <input type="text" name="customerName" placeholder="请输入客户名字"
                           class="layui-input" lay-verify="required"/>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">客户来源：</label>
                <div class="layui-input-block">
                    <select name="sourceSteamerId" id="sourceSteamerSelect" lay-verify="required">
                        <!-- 动态生成的 option 会插入在这里 -->
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">支付金额：</label>
                <div class="layui-input-block">
                    <input type="text" name="paymentAmount" placeholder="请输入支付金额"
                           class="layui-input" lay-verify="required"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">支付方式：</label>
                <div class="layui-input-block">
                    <select name="paymentMethod" lay-verify="required" dict-code="payment_method">
                        <option value="">所有</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">支付时间：</label>
                <div class="layui-input-block">
                    <div class="input-group date">
                        <input type="text" name="paymentTime" class="layui-input"
                               id="paymentTime" lay-verify="required">
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">下单图片：</label>
                <div class="layui-input-block">
                    <div id="image-preview" style="display: none;">
                        <img src="" alt="Order Image" id="image-preview-img"
                             style="width: 100px; height: auto; cursor: pointer;" onclick="viewImage(this.src)"/>
                    </div>

                    <button type="button" class="layui-btn layui-btn-normal" id="upload-image-btn"
                            style="background-color: #36b368;margin-top: 10px">
                        <i class="layui-icon">&#xe67c;</i> 上传图片
                    </button>

                    <input type="hidden" name="paymentScreenshot" id="orderImage"/>
                </div>
            </div>


        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                    lay-filter="customerInfo-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="pear-btn pear-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>
</body>
<script th:src="@{/admin/js/axios.min.js}"></script>
<script th:src="@{/admin/js/requests.js}"></script>
<script th:src="@{/admin/api/role.js}"></script>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">

    layui.use(['form', 'jquery', 'laydate', 'dictionary', 'upload'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let laydate = layui.laydate;
        let upload = layui.upload;

        let prefix = "/sys/customerInfo/"

        laydate.render({
            elem: '#paymentTime'
        });
        laydate.render({
            elem: '#createdAt'
        });
        laydate.render({
            elem: '#updatedAt'
        });
        let params = {}
        params.roleCode = "manager"
        // 调用 API 获取数据
        listRoleByCodeApi(params).then(res => {
            console.log(res.data);

            // 获取 select 元素
            const selectElement = document.getElementById('sourceSteamerSelect');

            // 清空现有的选项
            selectElement.innerHTML = '';

            // 遍历 API 返回的数据，动态添加 option 元素
            res.data.forEach(item => {
                const option = document.createElement('option');
                option.value = item.userId; // 假设 API 返回数据项包含 `id` 字段
                option.innerHTML = item.realName; // 假设 API 返回数据项包含 `name` 字段
                selectElement.appendChild(option);
            });

            // 如果你需要默认选中某个选项，可以通过以下方式设置：
            // selectElement.value = res.data[0].userId;  // 替换为你需要默认选中的 `id`
            form.render('select');
        }).catch(err => {
            console.error('API 请求失败:', err);
        });


        var uploadInst = upload.render({
            elem: '#upload-image-btn',  // Upload button
            url: '/upload/image',  // Server-side upload URL (replace with your actual URL)
            accept: 'images',  // Only allow image files
            done: function (res) {
                // Success callback: Display the uploaded image preview
                if (res.success) {
                    var imageUrl = res.data;  // Assuming the response contains the image URL in `res.data.url`
                    $('#orderImage').val(imageUrl);  // Set the image URL in the hidden input field
                    $('#image-preview').show();  // Show the image preview
                    $('#image-preview-img').attr('src', imageUrl);  // Set the preview image source
                } else {
                    layer.msg(res.msg, {icon: 2, time: 1000});  // Show error message
                }
            },
            error: function () {
                layer.msg("上传失败", {icon: 2, time: 1000});
            }
        });


        form.on('submit(customerInfo-save)', function (data) {
            for (var key in data.field) {
                var type = $(data.form).find("input[name='" + key + "']").attr("type");
                if (type == "checkbox") {
                    var value = "";
                    $(data.form).find("input[name='" + key + "']:checked").each(function () {
                        value += $(this).val() + ",";
                    })
                    if (value != "") {
                        value = value.substr(0, value.length - 1);
                        data.field[key] = value;
                    }

                }
            }
            $.ajax({
                url: prefix + 'save',
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    if (result.success) {
                        layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            parent.layui.table.reload("customerInfo-table");
                        });
                    } else {
                        layer.msg(result.msg, {icon: 2, time: 1000});
                    }
                }
            })
            return false;
        });
    });
</script>
</html>